package main

import (
	proto "com/hr/go-muke/gin/proro"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	en_tran "github.com/go-playground/validator/v10/translations/en"
	zh_tran "github.com/go-playground/validator/v10/translations/zh"
	"reflect"
	"strings"
	"time"

	"net/http"
)

type LoginForm struct {
	User     string `json:"user" form:"user" binding:"required,min=3"`
	Password string `json:"password" form:"user"  binding:"required"`
}
type RegisterForm struct {
	Age        uint8  `json:"age" binding:"gte=1,lte=130"`
	Name       string `json:"name" binding:"required,min=3"`
	Email      string `json:"email" binding:"required,email"`
	Password   string `json:"password" binding:"required"`
	RePassword string `json:"re_password" binding:"required,eqfield=Password"`
}

var trans ut.Translator

// InitTrans 注册翻译器
func InitTrans(local string) (err error) {
	//修改gin框架的validator引擎属性，实现定制
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		v.RegisterTagNameFunc(func(field reflect.StructField) string {
			name := strings.SplitN(field.Tag.Get("json"), ",", 2)[0]
			if name == "-" {
				return ""
			}
			return name
		})
		zh := zh.New()
		en := en.New()
		//第一个参数是备用语言环境
		uni := ut.New(en, zh, en)
		trans, ok = uni.GetTranslator(local)
		if !ok {
			return fmt.Errorf("uni.GetTranslator(%s)", local)
		}
		switch local {
		case "en":
			err := en_tran.RegisterDefaultTranslations(v, trans)
			if err != nil {
				return err
			}
		case "zh":
			err := zh_tran.RegisterDefaultTranslations(v, trans)
			if err != nil {
				return err
			}
		default:
			err := en_tran.RegisterDefaultTranslations(v, trans)
			if err != nil {
				return err
			}
		}
		return err
	}
	return err
}
func removeTopStruct(fields map[string]string) map[string]string {
	rsp := map[string]string{}
	for f, err := range fields {
		rsp[f[strings.Index(f, ".")+1:]] = err
	}
	return rsp
}

// MyLogger 自定义中间件
func MyLogger() gin.HandlerFunc {
	return func(c *gin.Context) {
		t := time.Now()
		c.Set("example", "123456")
		c.Next()
		end := time.Since(t)
		fmt.Printf("耗时：%v\n", end)
		status := c.Writer.Status()
		fmt.Println("状态:", status)
	}
}
func main() {
	if err := InitTrans("zh"); err != nil {
		fmt.Println("初始化翻译器错误", err)
		return
	}
	server := gin.Default()
	server.GET("/moreJson", moreJson)
	server.GET("/moreProto", moreProto)
	server.POST("/loginJSON", func(c *gin.Context) {
		var loginForm LoginForm
		if err := c.ShouldBind(&loginForm); err != nil {
			errors, ok := err.(validator.ValidationErrors)
			if !ok {
				c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			}
			c.JSON(http.StatusBadRequest, gin.H{"error": removeTopStruct(errors.Translate(trans))})
			return
		}
		c.JSON(http.StatusOK, gin.H{"msg": "登录成功"})
	})
	server.POST("/register", func(c *gin.Context) {
		var reg RegisterForm
		if err := c.ShouldBind(&reg); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"msg": "注册成功"})
	})
	err := server.Run(":9999")
	if err != nil {
		return
	}
}

func moreProto(c *gin.Context) {
	t := proto.Teacher{Name: "胡冉", Course: "Java"}
	c.ProtoBuf(http.StatusOK, &t)
}

func moreJson(c *gin.Context) {
	var msg struct {
		Name    string `json:"user"`
		Message string
		Number  int
	}
	msg.Name = "胡冉"
	msg.Message = "AAA"
	msg.Number = 10
	c.JSON(http.StatusOK, msg)
}
